package com.wande.dataplatform.filecollection.transform.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.dataplatform.filecollection.transform.ITransformFunction;
import org.springframework.stereotype.Component;

/**
 * 字符串截取函数
 *
 * @author wande
 */
@Component
public class SubstringFunction implements ITransformFunction {

    @Override
    public String getName() {
        return "SUBSTRING";
    }

    @Override
    public String getDescription() {
        return "截取字符串，参数: {\"start\": 0, \"end\": 10}";
    }

    @Override
    public Object transform(Object value, String params) {
        if (value == null) {
            return null;
        }

        String str = value.toString();
        
        // 解析参数
        int start = 0;
        Integer end = null;
        if (params != null) {
            JSONObject json = JSONUtil.parseObj(params);
            start = json.getInt("start", 0);
            end = json.getInt("end");
        }

        // 截取字符串
        if (end != null) {
            return str.substring(start, Math.min(end, str.length()));
        } else {
            return str.substring(start);
        }
    }
}
